using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyShooter : MonoBehaviour
{
    [Header("Characteristics")]
    public int health;
    public int damage;
    private float speed;
    public float normalSpeed;
    public float stopInterval;
    private float stopTime;

    [Header("Reloading")]
    public float startTimeBtwAttack;
    private float timeBtwAttack;

    private Animator anim;
    private PlayerController player;
    private PlayerController SecondPlayer;
    [HideInInspector] public bool facingRight = true;
    [SerializeField] private GameObject bullet;
    [SerializeField] private Transform shotPoint;
    private Transform weapon;
    private AddRoom room;
    private Vector3 difference;

    [Header("Effects")]
    public GameObject floatingDamage;
    public GameObject deathEffect;

    // Получение объектов из окружения
    private void Start() {
        player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();
        if (PlayerPrefs.GetInt("playersCount") > 1) SecondPlayer = GameObject.FindGameObjectWithTag("SecondPlayer").GetComponent<PlayerController>();
        weapon = gameObject.transform.Find("Weapon 5");
        room = GetComponentInParent<AddRoom>();
    }

    private void Update() {   
        if (stopTime <= 0) { // Счётчик возобновления движения врагаы
            speed = normalSpeed;
        } else {
            speed = 0;
            stopTime -= Time.deltaTime;
        }

        if (health <= 0) { // Смерть врага
            Instantiate(deathEffect, transform.position, Quaternion.identity);
            player.textScore.text = "SCORE: " + (player.score += 1);        
            Destroy(gameObject); 
            room.enemies.Remove(gameObject);
        }

        //Поворот врага
        if (player.transform.position.x > transform.position.x) {
            transform.eulerAngles = new Vector3(0, 0, 0);
            facingRight = true;
        }
        else {
            transform.eulerAngles = new Vector3(0, 180, 0);
            facingRight = false;
        }

        // Движение врага на игрока
        transform.position = Vector2.MoveTowards(transform.position, player.transform.position, speed * Time.deltaTime);

        // Обработка поворота оружия
        if (PlayerPrefs.GetInt("playersCount") > 1) {
            Vector3 difference_first = player.transform.position - transform.position;
            Vector3 difference_second = SecondPlayer.transform.position - transform.position;
            difference = Vector3.Min(difference_first, difference_second);
        } else {
            difference = player.transform.position - transform.position;
        }

        float flip = facingRight ? 1 : -1;
        float rotz = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;

        if (facingRight == true && rotz < 50 && rotz > -60) { // Ограничение угла поворота
            weapon.rotation = Quaternion.Euler(0f, 0f, rotz);
        } else if (facingRight == false) {
            weapon.rotation = Quaternion.Euler(0f, 0f, rotz);
        }

        // Выстрел и перезарядка
        if (timeBtwAttack <= 0) Shoot();
        else timeBtwAttack -= Time.deltaTime;
    }

    // Нанесение урона
    public void TakeDamage(int damage) {
        stopTime = stopInterval;
        health -= damage;
        Vector2 damagePos = new Vector2(transform.position.x + 1f, transform.position.y + 1f);
        Instantiate(floatingDamage, damagePos, Quaternion.identity);
        floatingDamage.GetComponentInChildren<FloatingDamage>().damage = damage;

        //Instantiate(deathEffect, player.transform.position, Quaternion.identity);
    }

    public void Shoot() {
        //Создание экземпляра снаряда на указанной точке выстрела
        Instantiate(bullet, shotPoint.position, shotPoint.rotation);
        timeBtwAttack = startTimeBtwAttack; //Сброс задержки
    }
}
